using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Catalog.Application.Brands.Commands;
using Catalog.Application.Brands.Interfaces;
using Catalog.Application.Interfaces;
using MediatR;

namespace Catalog.Application.Brands.CommandHandlers;

public class ChangeBrandNameCommandHandler : IRequestHandler<ChangeBrandNameCommand, Unit>
{
    private readonly IBrandRepository _brandRepository;
    private readonly IUnitOfWork _unitOfWork;

    public ChangeBrandNameCommandHandler(IBrandRepository brandRepository, IUnitOfWork unitOfWork)
    {
        _brandRepository = brandRepository;
        _unitOfWork = unitOfWork;
    }


    public async Task<Unit> Handle(ChangeBrandNameCommand request, CancellationToken cancellationToken)
    {
        var brand = await _brandRepository.GetByIdAsync(request.id);
        if (brand == null)
            throw new KeyNotFoundException("品牌不存在！");

        brand.ChangeName(request.newName);
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return Unit.Value;

    }
}